package com.wuren.foodshare.service.impl;

import com.wuren.foodshare.dao.UserDao;
import com.wuren.foodshare.dao.UserRoleDao;
import com.wuren.foodshare.entity.User;
import com.wuren.foodshare.entity.UserRole;
import com.wuren.foodshare.service.UserService;
import com.wuren.foodshare.util.PasswordEncoderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRoleDao userRoleDao;


    @Override
    @Transactional
    public String addUser(User user) {
        //判断用户名是否存在
        User is_Exist = userDao.findByUsername(user.getUsername());
        if(is_Exist == null){
            user.setPassword(PasswordEncoderUtil.encodePassword(user.getPassword()));  //密码加密
            userDao.addUser(user); //添加用户，返回插入数据的用户id
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(1);
            userRoleDao.addUserRole(userRole);
            return "success";
        }else {
            return "User already exist";
        }
    }
}
